package com.longcai.cm.api.listener;

import cn.hutool.core.thread.ThreadUtil;
import com.longcai.cm.common.utils.StringUtils;
import com.longcai.cm.delay.OrderDelay;
import com.longcai.cm.delay.SecKillGoodDelay;
import com.longcai.cm.domain.JaGoodsInfo;
import com.longcai.cm.domain.JaOrder;
import com.longcai.cm.service.JaGoodsInfoService;
import com.longcai.cm.service.JaMemberAssetService;
import com.longcai.cm.service.JaMemberCouponsService;
import com.longcai.cm.service.JaOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.DelayQueue;

/**
 * @author libingxing
 */
@Component
@Order(11)
public class OrderDelayConsumer implements InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private DelayQueue<OrderDelay> orderDelayQueue;

    @Resource
    private JaOrderService orderService;

    @Resource
    private JaMemberAssetService memberAssetService;

    @Resource
    private JaMemberCouponsService memberCouponsService;

    @Override
    public void afterPropertiesSet() {
        ThreadUtil.execAsync(() ->
                {
                    while (true) {
                        try {
                            final OrderDelay task = orderDelayQueue.take();
                            final String orderId = task.getOrderId();
                            final JaOrder order = orderService.getById(orderId);
                            if (order.getOrderStatus() < 1) {
                                logger.info("订单：" + orderId + "进入取消操作");
//                                积分抵扣
                                if (order.getIntegral() != null && order.getIntegral() > 0) {
                                    memberAssetService.updateMemberAssetIntegral(order.getMemberId() + "", new BigDecimal(order.getIntegral()), 1, order.getShopName() + order.getGoodName() + "，订单取消积分退还");
                                }
//                                优惠券
                                if (StringUtils.isNotBlank(order.getCouponId())) {
                                    memberCouponsService.changeUseStatusToCancel(order.getCouponId());
                                }
                                orderService.lambdaUpdate()
                                        .eq(JaOrder::getId, orderId)
                                        .set(JaOrder::getOrderStatus, 4)
                                        .update();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.info("秒杀商品延时任务异常跳过" + e.getMessage());
                        }
                    }
                }
        );
    }
}
